import React, {Component} from 'react';
import { StyleSheet, Text, View, Modal, Button, Image, TouchableHighlight, FlatList, ScrollView} from 'react-native';
import Header from '../../../component/header/header'
import { px2dp } from '../../../utils/util'
import api from '../../../common/net/api'
import server from '../../../common/net/server'
/**
 * 代理
 */
export default class AboutUs extends Component{
  constructor (props) {
    super(props)
    this.state = {
      is_number: 0,
      bet_one: {},
      timer: '',
      isend: '000000',
      isModal: false,
      isModal2: false,
      isModal3: false,
      fiveList: [],
      jiantou: require('../../../assets/login/icon_right.png'),
      btnList: [
        {
          text: '龙',
          num: 1,
          isChoice: false
        },
        {
          text: '虎',
          num: 2,
          isChoice: false
        },
        {
          text: '和',
          num: 3,
          isChoice: false
        }
      ],
      checkList: [],
      tabList: [{
        text: '走势图',
        router: 'TxffcDetails'
      }, {
        text: '追号记录',
        router: 'TxffcDetails'
      }, {
        text: '开奖信息',
        router: 'TxffcDetails'
      }, {
        text: '玩法介绍',
        router: 'TxffcDetails'
      }]
    }
  }

  componentDidMount() {
    //添加监听
    this.viewDidAppear = this.props.navigation.addListener(
      'didFocus',
      (obj)=>{
        this._getTime()
        this._getList()
        console.log('页面已经显示')
      }
    )
    this.viewDidAppear2 = this.props.navigation.addListener(
      'willBlur',
      (obj)=>{
        clearTimeout(this.state.timer)
        console.log('页面将要移除')
      }
    )
  }

  /**
   * 销毁定时命令
   */
  componentWillUnmount () {
    clearTimeout(this.state.timer)
    this.viewDidAppear.remove()
    this.viewDidAppear2.remove()
  }
  /**
   * 获取时间
   */
  _getTime () {
    server.post(api.login.getBetOne, {
      cp_key: 'txffc'
    }).then(res =>{
      this.setState({
        is_number: parseInt(res.data.bet_time),
        bet_one: res.data
      })
      this.is_endtime(res.data)
    }).catch(err => {
      console.log(err)
    })
  }

  /**
   * 获取数据
   */
  _getList () {
    let par = {
      cp_key: 'txffc',
      page: 1,
      page_size: 5
    }
    server.post(api.txffc.getPrizeList, par).then(res =>{
      this.setState({
        fiveList: res.data.datas
      })
    }).catch(err => {})
  }

  /**
   * 倒计时
   */
  is_endtime () {
    let last_time = this.state.is_number
    let new_time = ''
    if (last_time === 0) {
      new_time = '0000'
      clearTimeout(this.state.timer)
      this.setState({
        isModal: true
      })
    } else {
      const px_d=60*60*24;// 天
      const px_h=60*60;  //小时
      const px_m=60; //分
      const px_s=1;  //秒
      let m=Math.floor((last_time)/px_m)>=10?Math.floor((last_time)/px_m):'0'+Math.floor((last_time)/px_m);
      let s=Math.floor((last_time-m*px_m)/px_s)>=10?Math.floor((last_time-m*px_m)/px_s):'0'+Math.floor((last_time-m*px_m)/px_s);
      new_time=m+''+s
      this.setState({
        timer: setTimeout(() => {
          this.setState({
            is_number: last_time - 1
          })
          this.is_endtime()
        }, 5000)
      })
    }
    this.setState({
      isend: new_time
    })
  }

  _renderBtn (item, index) {
    let btnList = this.state.btnList
    let checkList = []
    if (item.isChoice) {
      return (
        <View style={{flex: 1, alignItems: 'center'}}>
        <TouchableHighlight
          onPress={() => {
            btnList[index].isChoice = false
            btnList.forEach(e => {
              if (e.isChoice) {
                checkList.push(e)
              }
            })
            this.setState({
              btnList: btnList,
              checkList: checkList
            })
          }}
          underlayColor='#ff473a'
          style={{
            width: px2dp(100),
            height: px2dp(100),
            borderRadius: px2dp(50),
            borderColor: '#e9e9e9',
            borderWidth: 1,
            backgroundColor: 'red',
            justifyContent: 'center'
          }}>
          <Text style={{textAlign: 'center', color: 'white'}}>{item.text}</Text>
        </TouchableHighlight>
      </View>
      )
    }
    return (
      <View style={{flex: 1, alignItems: 'center'}}>
        <TouchableHighlight
          onPress={() => {
            // this.onPressClick(true)
            btnList[index].isChoice = true
            btnList.forEach(e => {
              if (e.isChoice) {
                checkList.push(e)
              }
            })
            this.setState({
              btnList: btnList,
              checkList: checkList
            })
          }}
          underlayColor='white'
          style={{
            width: px2dp(100),
            height: px2dp(100),
            borderRadius: px2dp(50),
            borderColor: '#e9e9e9',
            borderWidth: 1,
            justifyContent: 'center'
          }}>
          <Text style={{textAlign: 'center', color: '#333'}}>{item.text}</Text>
        </TouchableHighlight>
      </View>
    )
  }


  onPressClick (bloo) {
    let btnList = this.state.btnList
    let checkList = []
    btnList[index].isChoice = bloo
    btnList.forEach(e => {
      if (e.isChoice) {
        checkList.push(e)
      }
    })
    this.setState({
      btnList: btnList,
      checkList: checkList
    })
  }

  _renderXuan (state) {
    let checkList = this.state.checkList
    let btnList = this.state.btnList
    let qk = require('../../../assets/image/clear_icon.png')
    let jx = require('../../../assets/image/random.png')
    if (checkList.length > 0) {
      return (
        <TouchableHighlight underlayColor='white' style={{justifyContent: 'center', backgroundColor: 'white', flex: 1}} onPress={() => {
          this.qkong()
        }}>
          <Image source={qk} style={{width: px2dp(160), height: px2dp(50)}}></Image> 
        </TouchableHighlight>
      )
    } else {
      return (
        <TouchableHighlight underlayColor='white' style={{justifyContent: 'center', backgroundColor: 'white', flex: 1}} onPress={() => {
          this.jxuan()
        }}>
          <Image source={jx} style={{width: px2dp(160), height: px2dp(50)}}></Image>  
        </TouchableHighlight>
      )
    }
  }

  jxuan () {
    let btnList = this.state.btnList
    let num = Math.floor(Math.random()*3)
    btnList.forEach((e, i) => {
      if (num == i) {
        e.isChoice = true
      }
    })
    this.setState({
      btnList: btnList,
      checkList: [btnList[num]]
    })
  }

  qkong () {
    let btnList = this.state.btnList
    btnList.forEach(e => {
      e.isChoice = false
    })
    this.setState({
      btnList: btnList,
      checkList: []
    })
  }

  _renderText () {
    let checkList = this.state.checkList
    if (checkList.length > 0) {
      let str = ''
      checkList.forEach(e => {
        str+=e.text
      });
      return (
        <View>
          <Text>已选{this.state.checkList.length}注</Text>
          <Text>{str}</Text>
        </View>
      )
    } else {
      return (
        <Text>已选{this.state.checkList.length}注</Text>
      )
    }
  }


  notShowModel () {
    this.setState({
      isModal: false
    })
    this._getTime()
    this._getList()
  }

  goPayment() {
    let checkList = this.state.checkList
    if (checkList.length > 0) {
      let { navigation } = this.props
      navigation.navigate('Payment')
    } else {
      this.jxuan()
    }
  }

  _renderRight () {
    let img = require('../../../assets/image/more_icon.png')
    return (
      <TouchableHighlight
        underlayColor='#ff473a'
        style={{height: '100%', justifyContent: 'center'}}
        onPress={() => {
          this.setState({
            isModal2: true
          })
        }}>
        <Image source={img} style={{width: px2dp(42), height: px2dp(10)}}></Image>
      </TouchableHighlight>
    )
  }

  goBack () {
    this.props.navigation.goBack()
  }

  _renderTime () {
    let time = this.state.isend
    let cp_which_number = this.state.bet_one.cp_which_number ? this.state.bet_one.cp_which_number.split('-')[1] : '0000'
    return (
      <View style={{flex: 1, alignItems: 'center'}}>
        <View style={{}}>
          <Text style={{fontSize: px2dp(20), textAlign: 'center'}}>———— 距离{cp_which_number}投注截止 ————</Text>
        </View>
        <View style={{flexDirection: 'row', marginTop: px2dp(20)}}>
          <Text style={styles.redView}>{time[0]}</Text>
          <Text style={styles.redView}>{time[1]}</Text>
          <Text> 分</Text>
          <Text style={styles.redView}>{time[2]}</Text>
          <Text style={styles.redView}>{time[3]}</Text>
          <Text> 秒</Text>
        </View>
      </View>
    )
  }

  render() {
    let arrowImg = this.state.jiantou
    let fiveList = this.state.fiveList
    let one_num = fiveList.length > 0 ? fiveList[0].cp_which_number.split('-')[1] : '0000'
    let numArr = fiveList.length > 0 ? fiveList[0].prize_number.split(',') : '00000'
    return (
      <View style={{backgroundColor: '#f4f4f4', flex: 1}}>
        <Header text="腾讯分分彩" goBack={() => {this.goBack()}} rightText={() => this._renderRight()}></Header>
        <ScrollView>
          <View style={styles.topView}>
            {this._renderTime()}
            <View style={{flex: 1, flexDirection: 'row'}}>
              <View style={{flex: 1, paddingLeft: px2dp(100)}}>
                <View style={{}}>
                  <Text style={{fontSize: px2dp(20)}}>{one_num}开奖结果</Text>
                </View>
                <View style={{flexDirection: 'row', marginTop: px2dp(15)}}>
                  <Text>{numArr[0]}</Text>
                  <Text>{numArr[1]}</Text>
                  <Text>{numArr[2]}</Text>
                  <Text>{numArr[3]}</Text>
                  <Text>{numArr[4]}</Text>
                </View>
              </View>
              <View style={{justifyContent: 'center', paddingRight: px2dp(20)}}>
                <Image source={arrowImg} style={{width: px2dp(20), height: px2dp(30)}}></Image>
              </View>
            </View>
          </View>
          <View style={{padding: px2dp(20),backgroundColor: 'white', marginTop: px2dp(20)}}>
            <Text>
              猜中开奖号码万位和个位的大小关系（万位大于个位为龙,万位小于个位为虎,万位等于个位为和）,龙中奖<Text style={{color: 'red'}}>4.0元</Text>,虎中奖<Text style={{color: 'red'}}>4.3元</Text>,和中奖<Text style={{color: 'red'}}>19.4元</Text>
            </Text>
            <FlatList
              style={{paddingTop: px2dp(40), paddingBottom: px2dp(20)}}
              data={this.state.btnList}
              numColumns = {3}
              extraData={this.state}
              renderItem={({item, index}) => this._renderBtn(item, index)}
              ></FlatList>
          </View>
        </ScrollView>
        <View style={{height: px2dp(100), flexDirection: 'row'}}>
          <View>
            {this._renderXuan(this.state)}
          </View>
          <View style={{flex: 1, justifyContent: 'center', backgroundColor: 'white', paddingLeft: px2dp(20), paddingRight: px2dp(20)}}>
            {this._renderText()}
          </View>
          <TouchableHighlight
            style={{width: px2dp(200),backgroundColor: 'red', justifyContent: 'center', alignItems: 'center'}}
            underlayColor='red'
            onPress={() => {
              this.goPayment()
            }}>
            <Text style={{color: 'white'}}>确定</Text>
          </TouchableHighlight>
        </View>
        <Modal
          transparent={true}
          visible={this.state.isModal}
          >
          <View style={styles.modelView}>
            <View style={{backgroundColor: 'white'}}>
              <Text>尊敬的用户,当前期已截止,期号已更新至下一期,请你核对期号后再投注.</Text>
              <Button title="我知道了" onPress={() => {
                this.notShowModel()
              }}></Button>
            </View>
          </View>
        </Modal>
        <Modal
          transparent={true}
          visible={this.state.isModal2}
          >
          <TouchableHighlight 
            style={{
              backgroundColor: 'rgba(00,00,00, 0.5)',
              flex: 1,
            }}
            underlayColor='rgba(00,00,00, 0.5)'
            onPress={() => {
            this.setState({
              isModal2: false
            })
          }}>
            <View style={{flexDirection: "row", marginTop: px2dp(80)}}>
              <View style={{flex: 1}}></View>
              <View style={{backgroundColor: 'white', width: px2dp(200)}}>
                <FlatList
                  data={this.state.tabList}
                  numColumns = {1}
                  extraData={this.state}
                  ItemSeparatorComponent={() => <View style={{backgroundColor: '#eee',height: 1}}></View>}  
                  renderItem={({item, index}) => {
                    return (
                      <TouchableHighlight
                        underlayColor='white'
                        onPress={() => {
                          this.setState({
                            isModal2: false
                          }, () => {
                            this.props.navigation.navigate(item.router)
                          })
                        }}>
                        <Text style={{textAlign: 'center', paddingVertical: px2dp(15)}}>{item.text}</Text>  
                      </TouchableHighlight>  
                    )
                  }}>
                </FlatList>
              </View>
            </View>
          </TouchableHighlight>
        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  topView: {
    flexDirection: 'row',
    paddingTop: px2dp(20),
    paddingBottom: px2dp(20),
    backgroundColor: 'white'
  },
  redView: {
    backgroundColor: '#ff473a',
    width: px2dp(40),
    height: px2dp(40),
    borderRadius: px2dp(4),
    textAlign: 'center',
    marginLeft: px2dp(10),
    color: 'white'
  },
  modelView: {
    backgroundColor: 'rgba(00,00,00, 0.5)',
    flex: 1,
    justifyContent: 'center'
  }
})